<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author lzw
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'operating:fstCase:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #fstCaseFollowList>
        <BasicTable
          @register="registerFstCaseFollowTable"
          @row-click="handleFstCaseFollowRowClick"
        />
        <a-button class="mt-2" @click="handleFstCaseFollowAdd" v-auth="'operating:fstCase:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
      <template #fstRepaymentTableList>
        <BasicTable @register="registerFstRepaymentTableTable" @row-click="handleFstRepaymentTableRowClick">
          <template #fstRepaymentTableUpload="{ record: childRecord }">
            <BasicUpload
              v-model:value="childRecord.dataMap"
              :bizKey="childRecord.id"
              :bizType="'fstRepaymentTable_file'"
              :uploadType="'all'"
              :loadTime="record.__t"
              :size="'small'"
            />
          </template>
        </BasicTable>
        <a-button class="mt-2" @click="handleFstRepaymentTableAdd" v-auth="'operating:fstCase:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsOperatingFstCaseForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { FstCase, fstCaseSave, fstCaseForm } from '/@/api/operating/fstCase';
  import { BasicUpload } from '/@/components/Upload';
  import { useDict } from '/@/components/Dict';

  const { initDict } = useDict();
  const emit = defineEmits(['success', 'register']);
  const { t } = useI18n('operating.fstCase');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<FstCase>({} as FstCase);
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增案件表') : t('编辑案件表'),
  }));

  const inputFormSchemas: FormSchema[] = [
  {
      label: '原始案件信息',
      field: 'detailInfo',
      component: 'Divider',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: '客户姓名',
      field: 'name',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '数据来源',
      field: 'caseSource',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '放款银行',
      field: 'bank',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '订单号',
      field: 'orderId',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '联系电话',
      field: 'phone',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '身份证号',
      field: 'idCard',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '放款金额',
      field: 'loanAmount',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '剩余本金',
      field: 'oddCorpus',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '剩余利息',
      field: 'residualInterest',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '债权方',
      field: 'spv',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '处置信息',
      field: 'detailInfo',
      component: 'Divider',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: '户籍地法院',
      field: 'court',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '还款账户信息',
      field: 'accountInformation',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: t('还款方式'),
      field: 'modeRepayment',
      component: 'Select',
      componentProps: {
        dictType: 'modeOfRepayment',
        allowClear: true,
      },
    },
    {
      label: '应还款金额',
      field: 'negotiatedInterest',
      component: 'Text',
      componentProps: {
        isHtml: false,
      },
    },
    {
      label: '案件跟进',
      field: 'detailInfo',
      component: 'Divider',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'fstCaseFollowList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'fstCaseFollowList',
    },
    {
      label: '还款管理',
      field: 'detailInfo',
      component: 'Divider',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'fstRepaymentTableList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'fstRepaymentTableList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerFstCaseFollowTable, fstCaseFollowTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleFstCaseFollowDelete.bind(this, record),
          },
          auth: 'operating:fstCase:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setFstCaseFollowTableData(_res: Recordable) {
    await initDict(['follow_up']);
    fstCaseFollowTable.setColumns([
      {
        title: t('跟进时间'),
        dataIndex: 'followUpTime',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: true,
      },
      {
        title: t('跟进情况'),
        dataIndex: 'type',
        width: 130,
        align: 'center',
        dictType: 'follow_up',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'follow_up',
          allowClear: true,
          immediate: true,
        },
        editRule: true,
      },
      {
        title: t('详细描述'),
        dataIndex: 'detail',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'InputTextArea',
        editComponentProps: {
          maxlength: 250,
        },
        editRule: false,
      },
    ]);
    fstCaseFollowTable.setTableData(record.value.fstCaseFollowList || []);
  }

  function handleFstCaseFollowRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleFstCaseFollowAdd() {
    fstCaseFollowTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleFstCaseFollowDelete(record: Recordable) {
    fstCaseFollowTable.deleteTableDataRecord(record);
  }

  async function getFstCaseFollowList() {
    let fstCaseFollowListValid = true;
    let fstCaseFollowList: Recordable[] = [];
    for (const record of fstCaseFollowTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        fstCaseFollowListValid = false;
      }
      fstCaseFollowList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of fstCaseFollowTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      fstCaseFollowList.push({
        ...record,
        status: '1',
      });
    }
    if (!fstCaseFollowListValid) {
      throw { errorFields: [{ name: ['fstCaseFollowList'] }] };
    }
    return fstCaseFollowList;
  }

  const [registerFstRepaymentTableTable, fstRepaymentTableTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleFstRepaymentTableDelete.bind(this, record),
          },
          auth: 'operating:fstCase:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setFstRepaymentTableTableData(_res: Recordable) {
    fstRepaymentTableTable.setColumns([
    {
        title: t('期数'),
        dataIndex: 'periods',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('应还款日期'),
        dataIndex: 'repaymentDate',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
      {
        title: t('应还款金额'),
        dataIndex: 'money',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 17,
        },
        editRule: false,
      },
      {
        title: t('实际还款日期'),
        dataIndex: 'actualRepaymentDate',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
      {
        title: t('实际还款金额'),
        dataIndex: 'actualRepaymentAmount',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 17,
        },
        editRule: false,
      },
      {
        title: t('还款凭证'),
        dataIndex: 'voucher',
        width: 160,
        align: 'center',
        slot: 'fstRepaymentTableUpload',
      },
      {
        title: t('是否确认入账'),
        dataIndex: 'isHx',
        width: 100,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        editRow: false,
      },
    ]);
    fstRepaymentTableTable.setTableData(record.value.fstRepaymentTableList || []);
  }

  function handleFstRepaymentTableRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleFstRepaymentTableAdd() {
    fstRepaymentTableTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleFstRepaymentTableDelete(record: Recordable) {
    fstRepaymentTableTable.deleteTableDataRecord(record);
  }

  async function getFstRepaymentTableList() {
    let fstRepaymentTableListValid = true;
    let fstRepaymentTableList: Recordable[] = [];
    for (const record of fstRepaymentTableTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        fstRepaymentTableListValid = false;
      }
      fstRepaymentTableList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of fstRepaymentTableTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      fstRepaymentTableList.push({
        ...record,
        status: '1',
      });
    }
    if (!fstRepaymentTableListValid) {
      throw { errorFields: [{ name: ['fstRepaymentTableList'] }] };
    }
    return fstRepaymentTableList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await fstCaseForm(data);
    record.value = (res.fstCase || {}) as FstCase;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setFstCaseFollowTableData(res);
    setFstRepaymentTableTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
        principalId: record.value.principalId,
      };
      data.fstCaseFollowList = await getFstCaseFollowList();
      data.fstRepaymentTableList = await getFstRepaymentTableList();
      // console.log('submit', params, data, record);
      const res = await fstCaseSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
